package com.xinhuo.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


/**
 *
 * @author 新林
 * @date 2016-1-19
 */
public class HttpRequest {
	/**
	 * 发起 http 请求获取返回结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpRequest(String requestUrl) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url
					.openConnection();
			httpUrlConn.setDoOutput(false);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
		}
		return buffer.toString();
	}

	/**
	 * utf 编码
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 聊天
	 * @param source
	 * @return
	 */
	public static String get(String requestUrl,Map<String, String> arr) {
		// 组装查询地址
		String json="";
		if(arr!=null){
			requestUrl+="?";
		}
		//String requestUrl = " http://www.tuling123.com/openapi/api?key=9e08afb5af3011c4164cacc0562c18e6&info={keyWord} ";
		// String requestUrl =
		// 对参数 q 的值进行 urlEncode utf-8 编码
		//requestUrl = requestUrl.replace("{keyWord}", urlEncodeUTF8(source));
		// 查询并解析结果
		Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();
			String key = entry.getKey();
			String val = entry.getValue();
			requestUrl +=  key + "=" + val +"&";
		}
		System.out.println("requestUrl="+requestUrl);
		try {
			// 查询并获取返回结果
			json = httpRequest(requestUrl);
			// 通过 Gson 工具将 json 转换成 TranslateResult 对象
			//System.out.println(json);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

//	public static void main(String[] args) {
//		// 翻译结果：The network really powerful
//		//System.out.println(chat("我是好人，你信么？"));
//		String url=urlEncodeUTF8("http://xinzhihuo.top/WeChatTransfer/servlet/transferServlet");
//		System.out.println(url);
//	}
}
